package com.caocaog.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.common.PushUtils;
import com.caocaog.market.entity.PushResult;
import com.caocaog.market.mapper.PushResultMapper;
import com.caocaog.market.service.PushResultService;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.res.statistic.StatisticDTO;
import org.jeecg.common.exception.JeecgBootException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 推送结果管理
 *
 * @author chechen
 * @date 2022-05-25
 */
@Service
@Transactional
public class PushResultServiceImpl extends ServiceImpl<PushResultMapper, PushResult> implements PushResultService {

    @Override
    public PushResult getPushResult(String date) {
        if (super.baseMapper.selectCount(new LambdaQueryWrapper<PushResult>().eq(PushResult::getDate, date)) > 0)
            return super.baseMapper.getPushResult(date);

        ApiResult<Map<String, Map<String, StatisticDTO>>> apiResult = PushUtils.statisticApi.queryPushResultByDate(date);
        if (apiResult.isSuccess()) {
            PushResult pushResult = new PushResult(apiResult.getData().get(date)).setDate(date);
            this.addPushResult(pushResult);
            return pushResult;
        } else {
            return null;
        }
    }

    @Override
    public void addPushResult(PushResult pushResult) {
        int insertRecordCount = super.baseMapper.insertPushResult(pushResult);
        if (insertRecordCount == 0)
            throw new JeecgBootException("新增推送结果失败");
    }

}
